package com.kos.snakerunningsystem.service.impl.utils;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class SnakePool extends Thread{
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();
    private final Queue<Snake> snakes = new LinkedList<>();


    public void addSnake(Integer userId, String snakeCode, String input){
        lock.lock();
        try{
            snakes.add(new Snake(userId,snakeCode,input));
            //假如添加失败不用唤醒线程，不用放到finally里
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    //创建一个新线程，方便控制执行时间，防止用户恶意破坏 死循环卡死程序
    private void consume(Snake snake){
        Consumer consumer = new Consumer();
        consumer.startTimeout(2000,snake);
    }

    @Override
    public void run() {
        while(true) {
            lock.lock();
            if(snakes.isEmpty()){
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    lock.unlock();
                    break;
                }
            } else{
                Snake snake = snakes.remove();
                lock.unlock();
                consume(snake);
            }
        }

        super.run();
    }
}

